<?php


namespace App\Controller\common;


use App\Common\Res;
use App\Constants\ErrorCode;
use App\Controller\AbstractController;
use App\Rpc\common\impl\UploadImpl;
use Hyperf\Utils\ApplicationContext;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use HyperfException\Json;

class UploadController extends AbstractController
{
    use Res;

    /**
     * 上传图片
     * @return array
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function uploadAvatar(): array
    {
        if (!$this->request->hasFile('avatar')) {
            return $this->Error(ErrorCode::DATA_NULL, '文件不存在');
        }
        if (!$this->request->file('avatar')->isValid()) {
            return $this->Error(ErrorCode::VALIDATE_PARAMS, '不是有效文件');
        }
//        $uri = $this->request->getUri();
//        $host = $uri->getHost();
        $avatar = $this->request->file('avatar');
        $params = $this->request->all();
        $res = ApplicationContext::getContainer()->get(UploadImpl::class)->uploadAvatar($avatar, $params);
        if ($res['code'] < 0)
            return $res['data'];
        return $res;
    }

    /**
     * 上传聊天图片
     * @return array
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function upload(): array
    {
        if (!$this->request->hasFile('file')) {
            return $this->Error(ErrorCode::DATA_NULL, '文件不存在');
        }
        if (!$this->request->file('file')->isValid()) {
            return $this->Error(ErrorCode::VALIDATE_PARAMS, '不是有效文件');
        }
        $file = $this->request->file('file');
        $params = $this->request->all();
        $res = ApplicationContext::getContainer()->get(UploadImpl::class)->uploadChatFile($file, $params);
        if ($res['code'] < 0)
            return $res['data'];
        return $res;
    }

}